//
//  SortedArray.m
//  MobileOA
//
//  Created by chenxiaojuan on 13-4-17.
//  Copyright (c) 2013年 chenxiaojuan. All rights reserved.
//

#import "sortedMutableArray.h"

@interface SortedMutableArray ()
@property(nonatomic,retain)NSMutableArray* array;
@property(nonatomic,assign)BOOL orderDesc;
@end

@implementation SortedMutableArray

@synthesize array;
@synthesize orderDesc;

-(id)initWithOrder:(BOOL)desc
{
    if ( self = [super init] )
    {
        self.array = [[[NSMutableArray alloc] init] autorelease];
        self.orderDesc = desc;
    }
    return self;
}

- (BOOL)append:(id)object{
    
    int nIndex = [self findPosition:object];
    
    if ( nIndex < 0 || !object )
        return NO;
    
    [self.array insertObject:object atIndex:nIndex];
    
    return YES;
}

- (BOOL)remove:(id)object{
    [self.array removeObject:object];
    
    return YES;
}

- (id)objectAtIndex:(int)pos
{
    return [self.array objectAtIndex:pos];
}

#pragma mark - private methods

- (int)findPosition:(id)object{
    if ([self.array count] < 1)
        return 0;
    
    int resultPositon = 0;
    int left = 0;
    int right = [self.array count] - 1;
    int middle = 0;
    int comp = 0;
    
    while (left <= right) {
        middle = (int)((left + right) / 2);
        id midObject = [self.array objectAtIndex:middle];
        
        //对象比较
        comp = [object compare:midObject];
        comp = self.orderDesc ? comp : -1 * comp;
        
        if (comp > 0) {//升序
            right = middle - 1;
        }else if (comp < 0){//降序
            left = middle + 1;
        }else{
            break;
        }
    }
    
    if (comp > 0) {
        resultPositon = middle;
    }else if (comp < 0){
        resultPositon = middle + 1;
    }else{
        resultPositon = -1 * middle - 1;
    }
    
    return resultPositon;
}

#pragma mark - propertys

-(int)count
{
    return array.count;
}

@end
